package com.lanxin.hr.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lanxin.hr.entity.JcBasicdatavalue;
import com.lanxin.hr.entity.ZzDepartment;
import com.lanxin.hr.entity.ZzDepartmentJob;
import com.lanxin.hr.entity.ZzEmployee;
import com.lanxin.hr.mapper.DepartmentJobVoMapper;
import com.lanxin.hr.service.IJcBasicdatavalueService;
import com.lanxin.hr.service.IZzDepartmentJobService;
import com.lanxin.hr.service.IZzDepartmentService;
import com.lanxin.hr.service.IZzEmployeeService;
import com.lanxin.hr.vo.DepartmentJobVo;
import com.lanxin.hr.vo.DeptVo;
import com.lanxin.hr.vo.PageVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.net.PortUnreachableException;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2025-07-21
 */
@Controller
@RequestMapping("/hr/zz-department")
public class ZzDepartmentController {

    private static final Logger log = LoggerFactory.getLogger(ZzDepartmentController.class);
    @Autowired
    private IZzDepartmentService departmentService;

    @Autowired
    private IZzDepartmentJobService departmentJobService;

    @Autowired
    private IJcBasicdatavalueService jcBasicdatavalueService;

    @Autowired
    private IZzEmployeeService employeeService;

    //查询所有部门信息,准备页面部门下拉栏数据
    @RequestMapping("/ListDeptVo")
    public ModelAndView ListDeptVo(@RequestParam(required = false) Integer page,@RequestParam(required = false) Integer pageSize,ZzDepartment department) {
        //根据条件分页查询部门信息
        PageVo<DeptVo> deptVos= departmentService.ListDeptVo(page,pageSize,department);
        ModelAndView modelAndView=new ModelAndView();
        //将前端表格条件回填进搜索条件表格中
        modelAndView.addObject("department",department);

        //拿到所有的部门名称以及id为部门管理页面的下拉栏填充数据
        List<ZzDepartment> parents=new ArrayList<>();
        List<ZzDepartment> departments=departmentService.listDepartment();
        for(ZzDepartment item:departments){
            ZzDepartment parent=new ZzDepartment();
            parent.setOid(item.getOid());
            parent.setDeptName(item.getDeptName());
            parents.add(parent);
        }

        modelAndView.addObject("parents",parents);
        modelAndView.addObject("deptVos",deptVos);
        modelAndView.setViewName("/hr/dept/listDept");
        return modelAndView;
    }

    //获取所有的部门信息用于下拉框
    @RequestMapping("/listDeptUseSelect")
    @ResponseBody
    public String listDeptUseSelect(){
        List<ZzDepartment> departments=departmentService.listDepartment();
        ObjectMapper mapper = new ObjectMapper();
        String deptJson = null;
        try {
            deptJson = mapper.writeValueAsString(departments);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return deptJson;
    }


    //跳转添加页面，准备数据
    @RequestMapping("/toAddDept")
    public ModelAndView toAddDept() {
        //获得所有的部门id和名称,填充下拉框
        List<ZzDepartment> parents= departmentService.getDeptName();

        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("parents",parents);
        modelAndView.setViewName("/hr/dept/addDept");
        return modelAndView;
    }

    //添加部门及部门职位对应表
    @RequestMapping("/addDept")
    public String addDept(ZzDepartment department,@RequestParam(required = false) List<Integer> jobsid) {
        ModelAndView modelAndView=new ModelAndView();
        try {
            //添加部门及对应的职位表
            departmentService.addDept(department,jobsid);
            //添加部门对应的职位表
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("部门添加失败");
        }
        return "redirect:/hr/zz-department/ListDeptVo";
    }

    //检测添加的部门是否已经存在
    @RequestMapping("/checkAddDept")
    @ResponseBody
    public String checkAddDept(String deptName) {
        boolean flag= departmentService.checkAddDept(deptName);
        ObjectMapper objectMapper=new ObjectMapper();
        String json=null;
        Map<String,Boolean> map=new HashMap<>();
        map.put("valid",flag);
        try {
            json=objectMapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return json;
    }

    //查看部门详情
    @RequestMapping("/deptInfo")
    public ModelAndView deptInfo(@RequestParam Integer oid){
        ModelAndView modelAndView=new ModelAndView();
        //查询部门信息
        DeptVo department = departmentService.getDeptVoById(oid);
        //查询部门下属职位
        List<DepartmentJobVo> jobs=departmentJobService.selectDepartmentJobByDId(oid.toString());
        modelAndView.addObject("department",department);
        modelAndView.addObject("jobs",jobs);
        modelAndView.setViewName("/hr/dept/deptDetail");
        return modelAndView;
    }

    //准备数据，跳转修改部门页面
    @RequestMapping("/toUpdateDept")
    public ModelAndView toUpdateDept(@RequestParam Integer oid){
        ModelAndView modelAndView=new ModelAndView();
        //获得所有的部门id和名称,填充下拉框
        List<ZzDepartment> parents= departmentService.getDeptName();
        //查询部门信息
        DeptVo department = departmentService.getDeptVoById(oid);
        //查询部门下属职位
        List<DepartmentJobVo> deptJobs=departmentJobService.selectDepartmentJobByDId(oid.toString());
        //查询所有的可用职位
        List<JcBasicdatavalue> jobs= jcBasicdatavalueService.getJobs();
        //获取尚有员工的职位
        List<Integer> usefulJobs=new ArrayList<>();
        for(DepartmentJobVo item:deptJobs){
            if(!employeeService.listEmpUseSelect(oid,item.getJobid()).isEmpty()){
                usefulJobs.add(item.getJobid());
            }
        }

        modelAndView.addObject("department",department);
        modelAndView.addObject("parents",parents);
        modelAndView.addObject("deptJobs",deptJobs);
        modelAndView.addObject("jobs",jobs);
        modelAndView.addObject("usefulJobs",usefulJobs);
        modelAndView.setViewName("/hr/dept/updateDept");
        return modelAndView;
    }

    //检测修改的名称是否已经存在，允许不修改名称只修改其他属性
    @RequestMapping("/checkUpdateDept")
    @ResponseBody
    public String checkUpdateDept(@RequestParam Integer oid,@RequestParam String deptName) {
        boolean flag=departmentService.checkUpdateDept(deptName,oid);
        Map<String,Boolean> map=new HashMap<>();
        map.put("valid",flag);
        ObjectMapper objectMapper=new ObjectMapper();
        String json=null;
        try {
            json=objectMapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return json;
    }

    //修改部门信息表,修改职位表
    @RequestMapping("/updateDept")
    @Transactional(propagation = Propagation.REQUIRED)
    public String updateDep(ZzDepartment department,@RequestParam List<Integer> jobsid) {
        //修改部门信息
        departmentService.updateById(department);
        /**
         * 修改职位信息-begin
         * */
        //删除原来的部门职位对应关系
        departmentJobService.deleteDepartmentJobByDId(department.getOid());

        //获取部门下的职位
        List<DepartmentJobVo> DepartmentJobVos = departmentJobService.selectDepartmentJobByDId(department.getOid().toString());
        List<Integer> jobIds=new ArrayList<>();
        for (DepartmentJobVo item : DepartmentJobVos) {
            jobIds.add(item.getJobid());
        }

        //存入新的职位信息
        for(Integer jobid:jobsid){
            ZzDepartmentJob departmentJob=new ZzDepartmentJob();
            departmentJob.setDeptid(department.getOid());
            departmentJob.setJobid(jobid);
            departmentJobService.addDeptJob(departmentJob);
        }
        /**
         * 修改职位信息-end
         * */
        return "redirect:/hr/zz-department/ListDeptVo";
    }


    //删除部门信息
    @RequestMapping("/deleteDept")
    @ResponseBody
    public String deleteDept(@RequestParam Integer oid){
        ObjectMapper objectMapper=new ObjectMapper();
        boolean flag=departmentService.deleteDeptById(oid);
        String s=null;
        try {
            s= objectMapper.writeValueAsString(flag);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return s;
    }
}
